package com.ceiec.trace.logback;

import ch.qos.logback.core.Layout;
import ch.qos.logback.core.encoder.EncoderBase;

import java.nio.charset.Charset;

/**
 * desc:
 *
 * @author : caokunliang
 * creat_date: 2018/9/12 0012
 * creat_time: 14:37
 **/
public class LogAggregatorEncoder<E> extends EncoderBase<E> {
    protected Layout<E> layout;

    private Charset charset;

    public Charset getCharset() {
        return charset;
    }

    public void setCharset(Charset charset) {
        this.charset = charset;
    }

    public Layout<E> getLayout() {
        return layout;
    }



    public void setLayout(Layout<E> layout) {
        this.layout = layout;
    }


    @Override
    public byte[] headerBytes() {
        return new byte[0];
    }

    @Override
    public byte[] encode(E event) {
        String txt = layout.doLayout(event);
        return convertToBytes(txt);
    }

    public String encode2Str(E event) {
        String txt = layout.doLayout(event);
        return txt;
    }

    private byte[] convertToBytes(String s) {
        if (charset == null) {
            return s.getBytes();
        } else {
            return s.getBytes(charset);
        }
    }

    @Override
    public byte[] footerBytes() {
        return new byte[0];
    }
}
